# -*- coding: utf-8 -*-
"""
角色管理业务逻辑层

负责角色、权限、销售员客户关系等相关的业务逻辑处理
"""
from typing import Dict, Any, Optional, List
from datetime import datetime, date
from app.repositories.role_repository import (
    RoleRepository, SalesmanRepository, CustomerRepository, 
    OrderRepository, SalesStatisticsRepository
)
from app.repositories.user_repository import UserRepository
from .config_service import config_service


class RoleService:
    """角色权限服务类"""
    
    def __init__(self):
        self.role_repo = RoleRepository()
        self.user_repo = UserRepository()
    
    def get_user_permissions(self, user_id: str) -> Dict[str, Any]:
        """获取用户权限信息"""
        user = self.user_repo.find_by_id("user_id", user_id)
        if not user:
            return {"permissions": [], "role": "customer"}
        
        user_role = user.get('user_role', 'customer')
        permissions = self.role_repo.get_user_permissions(user_role)
        page_permissions = self.role_repo.get_page_permissions(user_role)
        
        return {
            "role": user_role,
            "permissions": permissions,
            "page_permissions": page_permissions,
            "is_salesman": user_role == 'salesman',
            "is_customer": user_role == 'customer',
            "is_admin": user_role == 'admin',
            "can_manage_customers": user_role in ['salesman', 'admin'],
            "can_proxy_order": user_role in ['salesman', 'admin']
        }
    
    def check_permission(self, user_id: str, permission_code: str) -> bool:
        """检查用户是否有指定权限"""
        user = self.user_repo.find_by_id("user_id", user_id)
        if not user:
            return False
        
        user_role = user.get('user_role', 'customer')
        return self.role_repo.check_permission(user_role, permission_code)
    
    def check_page_access(self, user_id: str, page_path: str) -> bool:
        """检查用户是否可以访问指定页面"""
        user = self.user_repo.find_by_id("user_id", user_id)
        if not user:
            return False
        
        user_role = user.get('user_role', 'customer')
        page_permissions = self.role_repo.get_page_permissions(user_role)
        
        return page_path in page_permissions
    
    def switch_role(self, user_id: str, new_role: str, current_user_id: str) -> Dict[str, Any]:
        """用户角色切换"""
        # 检查操作权限
        if not self.check_permission(current_user_id, 'func.role.switch'):
            return {"success": False, "message": "无权限进行角色切换"}
        
        # 验证新角色有效性
        valid_roles = ['customer', 'salesman', 'admin']
        if new_role not in valid_roles:
            return {"success": False, "message": "无效的角色类型"}
        
        # 更新用户角色
        success = self.role_repo.update_user_role(user_id, new_role, current_user_id)
        
        if success:
            # 获取更新后的权限信息
            new_permissions = self.get_user_permissions(user_id)
            return {
                "success": True,
                "message": "角色切换成功",
                "data": {
                    "new_role": new_role,
                    "permissions": new_permissions
                }
            }
        else:
            return {"success": False, "message": "角色切换失败"}


class SalesmanService:
    """销售员服务类"""
    
    def __init__(self):
        self.salesman_repo = SalesmanRepository()
        self.customer_repo = CustomerRepository()
        self.stats_repo = SalesStatisticsRepository()
        self.role_service = RoleService()
    
    def get_salesman_dashboard(self, salesman_id: str) -> Dict[str, Any]:
        """获取销售员仪表板数据"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'page.salesman.dashboard'):
            raise PermissionError("无权限访问销售员仪表板")
        
        # 获取基本信息
        salesman = self.salesman_repo.get_salesman_by_id(salesman_id)
        if not salesman:
            raise ValueError("销售员信息不存在")
        
        # 获取今日统计
        today_stats = self.stats_repo.get_salesman_today_stats(salesman_id)
        
        # 获取客户列表
        customers = self.salesman_repo.get_salesman_customers(salesman_id)
        
        # 获取最近订单（通过OrderService获取）
        order_service = OrderService()
        recent_orders = order_service.get_salesman_orders(salesman_id, page=1, page_size=5)
        
        return {
            "salesman_info": {
                "user_id": salesman['user_id'],
                "nickname": salesman['nickname'],
                "salesman_no": salesman['salesman_no'],
                "department": salesman['department'],
                "salesman_level": salesman['salesman_level'],
                "hire_date": salesman['hire_date']
            },
            "today_stats": today_stats,
            "customer_count": len(customers),
            "customers": customers[:5],  # 显示前5个客户
            "recent_orders": recent_orders['orders']
        }
    
    def get_customer_list(self, salesman_id: str, page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取销售员的客户列表"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'api.customer.list'):
            raise PermissionError("无权限查看客户列表")
        
        return self.customer_repo.get_customers_list(salesman_id, page, page_size)
    
    def add_customer(self, salesman_id: str, customer_data: Dict[str, Any]) -> Dict[str, Any]:
        """销售员添加新客户"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'api.customer.create'):
            raise PermissionError("无权限创建客户")
        
        # 创建客户
        customer_id = self.customer_repo.create_customer(customer_data)
        if not customer_id:
            return {"success": False, "message": "创建客户失败"}
        
        # 建立销售员客户关系
        relation_id = self.salesman_repo.add_customer_to_salesman(
            salesman_id, customer_id, 'assigned', salesman_id
        )
        
        if relation_id:
            return {
                "success": True,
                "message": "客户添加成功",
                "data": {
                    "customer_id": customer_id,
                    "relation_id": relation_id
                }
            }
        else:
            return {"success": False, "message": "建立客户关系失败"}
    
    def switch_current_customer(self, salesman_id: str, customer_id: str) -> Dict[str, Any]:
        """切换当前服务的客户"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'func.customer.switch'):
            raise PermissionError("无权限切换服务客户")
        
        # 验证客户关系
        customers = self.salesman_repo.get_salesman_customers(salesman_id)
        customer_ids = [c['customer_id'] for c in customers]
        
        if customer_id not in customer_ids:
            return {"success": False, "message": "该客户不在您的服务范围内"}
        
        # 获取客户信息
        customer = next((c for c in customers if c['customer_id'] == customer_id), None)
        
        return {
            "success": True,
            "message": "切换客户成功",
            "data": {
                "current_customer": {
                    "customer_id": customer['customer_id'],
                    "nickname": customer['nickname'],
                    "phone": customer['phone'],
                    "wechat_nickname": customer['wechat_nickname'],
                    "wechat_avatar": customer['wechat_avatar']
                }
            }
        }
    
    def get_sales_statistics(self, salesman_id: str, start_date: Optional[str] = None, 
                           end_date: Optional[str] = None) -> Dict[str, Any]:
        """获取销售统计数据"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'api.sales.statistics'):
            raise PermissionError("无权限查看销售统计")
        
        # 转换日期
        start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None
        end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None
        
        # 获取统计数据
        statistics = self.stats_repo.get_salesman_statistics(salesman_id, start_date_obj, end_date_obj)
        
        # 计算汇总数据
        total_customers = 0
        total_orders = 0
        total_amount = 0
        total_commission = 0
        
        for stat in statistics:
            total_customers = max(total_customers, stat['customer_count'])
            total_orders += stat['order_count']
            total_amount += float(stat['order_amount'])
            total_commission += float(stat['commission_amount'])
        
        return {
            "statistics": statistics,
            "summary": {
                "total_customers": total_customers,
                "total_orders": total_orders,
                "total_amount": total_amount,
                "total_commission": total_commission,
                "avg_order_amount": total_amount / total_orders if total_orders > 0 else 0
            }
        }


class CustomerService:
    """客户服务类"""
    
    def __init__(self):
        self.customer_repo = CustomerRepository()
        self.salesman_repo = SalesmanRepository()
        self.role_service = RoleService()
    
    def get_customer_profile(self, customer_id: str, current_user_id: str) -> Dict[str, Any]:
        """获取客户资料"""
        # 权限检查：本人或有权限的销售员
        user_permissions = self.role_service.get_user_permissions(current_user_id)
        
        if customer_id != current_user_id and not user_permissions['can_manage_customers']:
            raise PermissionError("无权限查看该客户信息")
        
        # 获取客户信息
        customer = self.customer_repo.find_by_id("user_id", customer_id)
        if not customer:
            raise ValueError("客户信息不存在")
        
        # 获取服务销售员信息
        salesman_info = self.salesman_repo.get_customer_salesman(customer_id)
        
        return {
            "customer_info": customer,
            "salesman_info": salesman_info
        }
    
    def search_customers(self, keyword: str, current_user_id: str, salesman_filter: bool = True) -> List[Dict[str, Any]]:
        """搜索客户"""
        user_permissions = self.role_service.get_user_permissions(current_user_id)
        
        if not user_permissions['can_manage_customers']:
            raise PermissionError("无权限搜索客户")
        
        # 如果是销售员且启用筛选，只搜索自己的客户
        salesman_id = current_user_id if (user_permissions['is_salesman'] and salesman_filter) else None
        
        return self.customer_repo.search_customers(keyword, salesman_id)


class OrderService:
    """订单服务类"""
    
    def __init__(self):
        self.order_repo = OrderRepository()
        self.salesman_repo = SalesmanRepository()
        self.role_service = RoleService()
    
    def create_proxy_order(self, salesman_id: str, order_data: Dict[str, Any]) -> Dict[str, Any]:
        """销售员代理下单"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'api.order.proxy'):
            raise PermissionError("无权限代理下单")
        
        # 验证客户关系
        customer_id = order_data.get('customer_id')
        customers = self.salesman_repo.get_salesman_customers(salesman_id)
        customer_ids = [c['customer_id'] for c in customers]
        
        if customer_id not in customer_ids:
            return {"success": False, "message": "无法为该客户代理下单，请先建立客户关系"}
        
        # 设置订单数据
        order_data.update({
            'salesman_id': salesman_id,
            'created_by': salesman_id,
            'created_type': 'salesman'
        })
        
        # 创建订单
        order_id = self.order_repo.create_proxy_order(order_data)
        
        if order_id:
            return {
                "success": True,
                "message": "代理下单成功",
                "data": {"order_id": order_id}
            }
        else:
            return {"success": False, "message": "代理下单失败"}
    
    def get_salesman_orders(self, salesman_id: str, page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取销售员相关的订单"""
        # 检查权限
        if not self.role_service.check_permission(salesman_id, 'page.salesman.orders'):
            raise PermissionError("无权限查看订单")
        
        return self.order_repo.get_salesman_orders(salesman_id, page, page_size)
    
    def get_customer_orders(self, customer_id: str, current_user_id: str, page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取客户订单"""
        user_permissions = self.role_service.get_user_permissions(current_user_id)
        
        # 权限检查：本人或有权限的销售员
        if customer_id != current_user_id and not user_permissions['can_manage_customers']:
            raise PermissionError("无权限查看该客户订单")
        
        return self.order_repo.get_customer_orders(customer_id, page, page_size)


class PermissionMiddleware:
    """权限中间件"""
    
    def __init__(self):
        self.role_service = RoleService()
    
    def check_page_permission(self, user_id: str, page_path: str) -> Dict[str, Any]:
        """检查页面访问权限"""
        has_permission = self.role_service.check_page_access(user_id, page_path)
        
        if not has_permission:
            user_permissions = self.role_service.get_user_permissions(user_id)
            role = user_permissions['role']
            
            # 根据角色提供建议的跳转页面
            if role == 'customer':
                suggested_page = '/pages/user/profile'
                message = "您是客户用户，无法访问销售员功能"
            elif role == 'salesman':
                suggested_page = '/pages/salesman/dashboard'
                message = "您是销售员用户，无法访问该页面"
            else:
                suggested_page = '/pages/user/profile'
                message = "无权限访问该页面"
            
            return {
                "allowed": False,
                "message": message,
                "suggested_page": suggested_page,
                "user_role": role
            }
        
        return {"allowed": True}
    
    def get_navigation_menu(self, user_id: str) -> List[Dict[str, Any]]:
        """获取用户导航菜单"""
        user_permissions = self.role_service.get_user_permissions(user_id)
        role = user_permissions['role']
        
        if role == 'salesman':
            return [
                {"title": "销售仪表板", "path": "/pages/salesman/dashboard", "icon": "dashboard"},
                {"title": "客户管理", "path": "/pages/salesman/customers", "icon": "customers"},
                {"title": "订单管理", "path": "/pages/salesman/orders", "icon": "orders"},
                {"title": "个人中心", "path": "/pages/user/profile", "icon": "profile"}
            ]
        elif role == 'customer':
            return [
                {"title": "个人中心", "path": "/pages/user/profile", "icon": "profile"},
                {"title": "我的订单", "path": "/pages/user/orders", "icon": "orders"},
                {"title": "收货地址", "path": "/pages/user/addresses", "icon": "address"}
            ]
        elif role == 'admin':
            return [
                {"title": "销售仪表板", "path": "/pages/salesman/dashboard", "icon": "dashboard"},
                {"title": "客户管理", "path": "/pages/salesman/customers", "icon": "customers"},
                {"title": "订单管理", "path": "/pages/salesman/orders", "icon": "orders"},
                {"title": "个人中心", "path": "/pages/user/profile", "icon": "profile"},
                {"title": "我的订单", "path": "/pages/user/orders", "icon": "orders"},
                {"title": "收货地址", "path": "/pages/user/addresses", "icon": "address"}
            ]
        
        return [] 